package jp.androidgroup.chiba.androidresearch.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jp.androidgroup.chiba.androidresearch.aws.CounterManage;
import jp.androidgroup.chiba.androidresearch.data.Counter;
import jp.androidgroup.chiba.androidresearch.db.DatabaseHelper;
import jp.androidgroup.chiba.androidresearch.Common;
import jp.androidgroup.chiba.androidresearch.Constants;
import jp.androidgroup.chiba.androidresearch.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 過去の投稿ログを取得・表示するActivity
 */
public final class CounterLogActivity extends Activity {

	private Button btnNext;
	private Button btnBack;
	private ListView listView;

	private CounterManage mCounterManage;
	private ListAdapter mAdapter;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_counter_log);

		try {
			DatabaseHelper helper = new DatabaseHelper(this);
			mCounterManage = new CounterManage(this, helper, helper.getWritableDatabase());
		}
		// ここで例外発生時は何も描画しない
		catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
			return;
		}


		mAdapter = new ListAdapter(this, new ArrayList<Counter>());

		// 各ウィジェット初期化
		listView = (ListView) findViewById(R.id.list);
		listView.setAdapter(mAdapter);

		btnNext = (Button) findViewById(R.id.btn_next);
		btnNext.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				new CounterLoadTask(CounterLoadTask.NEXT).execute();
			}
		});

		btnBack = (Button) findViewById(R.id.btn_back);
		btnBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				new CounterLoadTask(CounterLoadTask.BACK).execute();
			}
		});

		// 読み込み
		new CounterLoadTask(CounterLoadTask.NEXT).execute();
	}




	final class CounterLoadTask extends AsyncTask<Void, String, List<Counter>> {

		/**
		 * 次の100件を読み込む場合
		 */
		public static final int NEXT = 0;
		/**
		 * 前の100件を読み込む場合
		 */
		public static final int BACK = 1;


		private ProgressDialog mProgressDialog;
		private final int mType;

		public CounterLoadTask(int type) {
			mType = type;

			if (mType != NEXT && mType != BACK) {
				throw new IllegalArgumentException("TaskType must be 0 or 1");
			}
		}

		@Override
		protected void onPreExecute() {
			mProgressDialog = new ProgressDialog(CounterLogActivity.this);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setMessage(getString(R.string.m_loading));
			mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					CounterLoadTask.this.cancel(true);
				}
			});

			mProgressDialog.show();
		}

		/*
		 * nullを返す：何らかの例外発生時
		 *
		 * (non-Javadoc)
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected List<Counter> doInBackground(Void... params) {

			try {
				return mType == NEXT ? mCounterManage.next(Constants.GET_COUNTER_LOG_NUMBER) : mCounterManage.back(Constants.GET_COUNTER_LOG_NUMBER);
			} catch (Exception e) {
				e.printStackTrace();
				publishProgress(new String[] {e.getMessage()});
				return null;
			}
		}

		@Override
		protected void onProgressUpdate(String... params) {
			Toast.makeText(CounterLogActivity.this, params[0], Toast.LENGTH_LONG).show();
		}

		@Override
		protected void onPostExecute(List<Counter> result) {
			mProgressDialog.dismiss();

			if (result == null) {
				result = new ArrayList<Counter>();
			}
			mAdapter.setData(result);
			mAdapter.notifyDataSetChanged();
			listView.setSelectionFromTop(0, 0);

			// ボタンの有効化
			btnNext.setEnabled(mCounterManage.isNextData());
			btnBack.setEnabled(mCounterManage.isBackData());
		}

	}


	/**
	 * リストアダプター for CounterLogActivity
	 *
	 * @author noxi
	 *
	 */
	static final class ListAdapter extends BaseAdapter {

		static final class ViewHolder {
			TextView date;
			TextView place;
			TextView memo;
			LinearLayout detail;
		}


		private List<Counter> mData;
		private final Context mContext;
		private final LayoutInflater mInflater;

		/**
		 * 詳細テキストの保存
		 */
		private Map<Integer, String[]> mDetails;


		public ListAdapter(Context context, List<Counter> data) {
			mData = data;
			mContext = context;
			mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			mDetails = new HashMap<Integer, String[]>();
		}

		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public Counter getItem(int position) {
			return mData.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public boolean isEnabled(int position) {
			return false;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.listitem_counter_log, parent, false);

				holder = new ViewHolder();
				holder.date = (TextView) convertView.findViewById(R.id.text_date);
				holder.place = (TextView) convertView.findViewById(R.id.text_place);
				holder.memo = (TextView) convertView.findViewById(R.id.text_memo);
				holder.detail = (LinearLayout) convertView.findViewById(R.id.layout_detail);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}


			Counter item = mData.get(position);

			// CustomDataのデータをViewの各Widgetにセットする
			holder.date.setText(item.getContributeDate() + " " + item.getUserName());
			holder.place.setText(Common.getPlaceList().get(item.getPlaceId()).getName()
					+ "　(" + Common.getTimeList().get(item.getTimeId()).getName() + ")");
			holder.memo.setText(item.getMemo());
			holder.detail.removeAllViews();

			if (item.getDetails() != null) {
				String[] details = mDetails.get(position);
				if (details == null) {
					details = new String[item.getDetails().size()];
					mDetails.put(position, details);
				}


				for (int i = 0 ; i < details.length ; i++) {
					if (details[i] == null) {
						Counter rowdata = item.getDetails().get(i);

						details[i] = "・" + Common.getUseList().get(rowdata.getUseId()).getName()
								+ "　" + mContext.getString(rowdata.getSex().equals("1") ? R.string.l_man : R.string.l_woman)
								+ "　" + Common.getOccList().get(rowdata.getOccupationId()).getName()
								+ "　" +rowdata.getNum() + mContext.getString(R.string.l_people_unit) + "\n";
						details[i] += "　　" + rowdata.getDetailMemo();
					}

					TextView text = new TextView(mContext);
					text.setText(details[i]);
					text.setTextSize(12.0f);

					holder.detail.addView(text);
				}
			}

			return convertView;
		}


		public void setData(List<Counter> data) {
			mData = data;
			mDetails = new HashMap<Integer, String[]>();
		}

	}
}
